package com.lyc.filter;

import com.lyc.util.UserUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter({"/admin/index.html", "/admin/views/*", "/express/*", "/courier/*", "/user/*"})
public class AccessControlFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String userName = UserUtil.getUserName(request.getSession());
        String requestURI = request.getRequestURI();
        if (requestURI.contains("index") && userName == null) {
            // 提示需要登录并跳转到登录界面
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println("<script>alert('请先登录！');top.location.href='/admin/login.html'</script>");
        } else {
            // 其他情况放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
